﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Xml;
using System.IO;
using System.Resources;
using System.Xml.Serialization;

namespace Ue.Components.FileResources
{
    public class XmlResourceReader : IResourceReader
    {
        public XmlResourceReader(string fileName)
        {
            this.Document = new XmlDocument();
            this.Document.Load(fileName);
        }

        public XmlDocument Document { get; private set; }

        public XmlResourceReader(Stream stream)
        {
            this.Document = new XmlDocument();
            this.Document.Load(stream);
        }

        public IDictionaryEnumerator GetEnumerator()
        {
            XmlNode root = this.Document.SelectSingleNode("resources");
            XmlAttribute rootTypeAttribute = root.Attributes["type"];

            Dictionary<string, object> set = new Dictionary<string, object>();
            foreach (XmlNode item in root.ChildNodes)
            {
                if (item.NodeType == XmlNodeType.Comment)
                    continue;

                var name = item.Attributes["name"].Value;
                XmlAttribute typeAttribute = item.Attributes["type"];
                if (typeAttribute == null)
                {
                    typeAttribute = rootTypeAttribute;
                }

                object value = typeAttribute == null
                    ? this.BuilderString(item)
                    : this.BuilderObject(item, Type.GetType(typeAttribute.Value));

                set.Add(name, value);
            }

            return set.GetEnumerator();
        }

        private object BuilderObject(XmlNode node,Type objectType)
        {
            object obj = null;

            XmlSerializer xmlSerializer = new XmlSerializer(objectType);
            using (StringReader reader = new StringReader(node.OuterXml))
            {
                obj = xmlSerializer.Deserialize(reader);
            }

            return obj;
        }

        private string BuilderString(XmlNode node)
        {
            var valueAttribute=node.Attributes["value"];

            return valueAttribute == null
                ? string.Empty
                : valueAttribute.Value;
        }

        #region IResourceReader
        
        IEnumerator IEnumerable.GetEnumerator()
        {
            return GetEnumerator();
        }

        public void Dispose() { }

        public void Close() { }

        #endregion
    }
}
